package com.jyy.businessapp;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.jyy.myserviceapp.IMyAidlInterface;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private Button mBtnBind;
    private Button mBtnUnBind;
    private Button mBtnStart;
    private Button mBtnStartApp;
    private Intent mServiceIntent;
    private IMyAidlInterface mBinder;
    private static boolean isRunning = false;
    private MyThread myThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(LogTag.TAG, "业务端: onCreate");
        mServiceIntent = new Intent();
        mServiceIntent.setComponent(new ComponentName("com.jyy.myserviceapp", "com.jyy.myserviceapp.MyService"));

        myThread = new MyThread();

        mBtnBind = findViewById(R.id.btn_bind);
        mBtnUnBind = findViewById(R.id.btn_unbind);
        mBtnStart = findViewById(R.id.btn_start);
        mBtnStartApp = findViewById(R.id.btn_start_app);

        mBtnBind.setOnClickListener(view -> {
            Log.d(LogTag.TAG, "业务端: 准备绑定服务");
            bindService(mServiceIntent, this, Context.BIND_AUTO_CREATE);
        });

        mBtnStart.setOnClickListener(view -> {
            if (!isRunning) {
                isRunning = true;
                myThread = new MyThread();
                myThread.start();
            }
        });

        mBtnStartApp.setOnClickListener(view -> {
            if (mBinder != null) {
                try {
                    mBinder.startApp("com.jyy.signapp.MainActivity");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(LogTag.TAG, "业务端: 服务未绑定...");
            }
        });

        mBtnUnBind.setOnClickListener(view -> {
            Log.d(LogTag.TAG, "业务端: 准备解绑服务");
            if (mBinder != null) {
                isRunning = false;
                try {
                    myThread.join(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                unbindService(this);
                mBinder = null;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBinder != null) {
            isRunning = false;
            try {
                myThread.join(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            unbindService(this);
            mBinder = null;
        }
    }

    @SuppressLint("DefaultLocale")
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.d(LogTag.TAG, "业务端: 绑定服务...");
        if (mBinder == null) {
            mBinder = IMyAidlInterface.Stub.asInterface(iBinder);
            try {
                // 获取当前时间戳（毫秒）
                long currentTimeMillis = System.currentTimeMillis();

                // 创建 SimpleDateFormat 对象，并指定日期时间格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

                // 将时间戳转换为 Date 对象
                Date date = new Date(currentTimeMillis);

                // 格式化 Date 对象为字符串
                String formattedDate = sdf.format(date);
                mBinder.setName(String.format("Hello Li: %s", formattedDate));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.d(LogTag.TAG, "业务端: 服务解绑...");
    }

    private final class MyThread extends Thread {
        @Override
        public void run() {
            while (isRunning) {
                if (mBinder != null) {
                    // 获取当前时间戳（毫秒）
                    long currentTimeMillis = System.currentTimeMillis();

                    // 创建 SimpleDateFormat 对象，并指定日期时间格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

                    // 将时间戳转换为 Date 对象
                    Date date = new Date(currentTimeMillis);

                    // 格式化 Date 对象为字符串
                    String formattedDate = sdf.format(date);
                    try {
                        mBinder.setName(String.format("Hello Li: %s", formattedDate));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.d(LogTag.TAG, "推送服务已退出...");
        }
    }
}